package com.anivia.system.auth.service.impl;

import com.anivia.common.core.constant.CommonStant;
import com.anivia.common.core.util.AssertUtil;
import com.anivia.common.core.util.BeanUtil;
import com.anivia.system.auth.mapper.DepartmentInfoMapper;
import com.anivia.system.auth.model.dto.DeptAddOrUpdateDTO;
import com.anivia.system.auth.model.entity.DepartmentInfoDO;
import com.anivia.system.auth.service.IDepartmentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 部门信息 服务实现类
 * </p>
 *
 * @author wangj
 */
@Service
public class DepartmentInfoServiceImpl extends ServiceImpl<DepartmentInfoMapper, DepartmentInfoDO> implements IDepartmentInfoService {

    @Override
    public void saveOrUpdate(DeptAddOrUpdateDTO dto) {
        if (dto.getPid() == null) {
            dto.setPid(CommonStant.TOP_ID);
        } else {
            if (!CommonStant.TOP_ID.equals(dto.getPid())) {
                DepartmentInfoDO dept = this.getById(dto.getPid());
                AssertUtil.notNull(dept, "父部门不存在");
            }
        }
        // 校验部门名称是否存在
        boolean existsName = this.lambdaQuery()
                .ne(dto.getId() != null, DepartmentInfoDO::getId, dto.getId())
                .eq(DepartmentInfoDO::getName, dto.getName())
                .exists();
        AssertUtil.isFalse(existsName, "名称已存在");

        DepartmentInfoDO departmentInfoDO = null;
        if (dto.getId() == null) {
            departmentInfoDO = BeanUtil.newBean(dto, DepartmentInfoDO.class);
        } else {
            departmentInfoDO = this.getById(dto.getId());
            AssertUtil.notNull(departmentInfoDO, "要更新的部门不存在");

            BeanUtil.copyProperties(dto, departmentInfoDO);
        }
        this.saveOrUpdate(departmentInfoDO);
    }

    @Override
    public void delete(Integer id) {
        // 检查部门是否存在
        DepartmentInfoDO dept = this.getById(id);
        AssertUtil.notNull(dept, "部门不存在");

        // 检查是否存在子部门
        boolean existsChildren = this.lambdaQuery().eq(DepartmentInfoDO::getPid, id).exists();
        AssertUtil.isFalse(existsChildren, "存在子部门，无法删除");

        // 检查部门下是否存在人员 TODO
        this.removeById(id);
    }
}
